package leetcode.string;

public class Lc43 {
    public String multiply(String num1, String num2) {
        if ("0".equals(num1) || "0".equals(num2)) return "0";
        if (num1.length() < num2.length()) {
            String temp = num1;
            num1 = num2;
            num2 = temp;
        }
        String revNum1 = new StringBuilder(num1).reverse().toString();
        String revNum2 = new StringBuilder(num2).reverse().toString();
        StringBuilder ans = new StringBuilder("0");
        for (int i = 0; i < num2.length(); i++) {
            StringBuilder res = multiply(revNum1, revNum2.charAt(i) - '0');
            StringBuilder preZero = new StringBuilder();
            for (int j = 0; j < i; j++) {
                preZero.append("0");
            }
            res = preZero.append(res);
            ans = add(res, ans);
        }
        return ans.reverse().toString();
    }

    //两个逆序整数相加，返回逆序和串
    private StringBuilder add(StringBuilder x, StringBuilder y) {

        int idx = 0;
        StringBuilder ans = new StringBuilder();
        int carry = 0;
        while (idx < x.length() || idx < y.length() || carry != 0) {
            int v1 = idx < x.length() ? x.charAt(idx) - '0' : 0;
            int v2 = idx < y.length() ? y.charAt(idx) - '0' : 0;
            int val = v1 + v2 +carry;
            ans.append(val % 10);
            carry = val / 10;
            idx++;
        }
        return ans;
    }
    //一个数字乘以一个长整数
    private StringBuilder multiply(String num1, int digit) {
        if (digit == 0) return new StringBuilder("0");
        int carry = 0;
        StringBuilder ans = new StringBuilder();
        for (int i = 0; i < num1.length(); i++) {
            int res = (num1.charAt(i) - '0') * digit + carry;
            ans.append((res) % 10);
            carry = res / 10;
        }
        if (carry != 0) ans.append(carry);
        return ans;
    }


    public static void main(String[] args) {
        Lc43 lc43 = new Lc43();
        System.out.println(lc43.multiply("123", "456"));
    }


}
